$(function() {
    var cart1 = {
        renderData: function(res, buyInfoList, orderRuleApplyInfos, orderRuleNotApplyInfos, tradeUpObjInfos, giveObjInfos, savedMoney) {

            // 购物车信息显示
            var buyInfoListTpl = '';
            if(buyInfoList.length == 0) {
                $('#cart_steps').hide();
                $('#cart_container').hide();
                $('.cart-empty').show();
                // $('#view_history').show();
            } else {
                $('#cart_steps').show();
                $('#cart_container').show();
                $.each(buyInfoList, function(index, item) {
                    var params = JSON.parse(item.params);
                    var liTpl = '';
                    $.each(item.ruleGoodsNames, function(indexDir, itemDir) {
                        if(itemDir.indexOf('strong') != -1) {
                            liTpl += '<li>'+itemDir.split('<strong>')[0]+'<p style="color:red;font-weight:bold;">'+itemDir.split('<strong>')[1].split('</')[0]+'</p></li>';
                        } else {
                            liTpl += '<li>'+itemDir+'</li>';
                        }
                    })
                    var shoucang = '';
                    if(item.fav) {
                        shoucang = '<span class="fav-on">已收藏</span>';
                    } else {
                        shoucang = '<a href="javascript:void(0);" class="btn-fav" data-role="addCartFav" data-goodsid="'+item.goodsId+'" data-productid="'+item.productId+'" data-name="'+params.productName+'" data-price="'+params.price+'" data-img="'+params.image.imageId+'">收藏</a>';
                    }
                    var tips = '';

                    if(item.count > item.store) {
                        tips = '该商品库存不足';
                    }
                    var shuliang = '';
                    var checkbox = '';
                    var huangou = '';
                    var zengpin = '';
                    var zengpinLink = '';
                    if(item.objSource == 'GIVE') {
                        zengpin = '<span style="color:red;">[赠品]</span>';
                        zengpinLink = '../info-give.html?goodsId='+item.goodsId+'&catId='+params.catId;
                    } else {
                        zengpinLink = '../info.html?goodsId='+item.goodsId+'&catId='+params.catId;
                    }
                    if(item.objSource == 'TRADE_UP') {
                        huangou = '<span style="color:red;">[换购]</span>'
                    }
                    if(item.objSource == 'GIVE' || item.objSource == 'TRADE_UP') {
                        shuliang = '<td><div class="p-quantity" style="width:100px;">'+item.count+'</div></td>';
                        checkbox = '<input name="goods" type="checkbox" style="display:none;"/>';
                    } else {
                        shuliang = '<td>\
                          <div class="p-quantity">\
                            <a href="javascript:void(0);" class="btn-decrease" data-total="'+item.store+'" data-page="cart1" data-goodsid="'+item.goodsId+'" data-productid="'+item.productId+'" data-objtype="'+item.objType+'">-</a>\
                            <input type="text" class="action-quantity-input" value="'+item.count+'" data-total="'+item.store+'" data-page="cart1" data-goodsid="'+item.goodsId+'" data-productid="'+item.productId+'" data-objtype="'+item.objType+'">\
                            <a href="javascript:void(0);" class="btn-increase" data-total="'+item.store+'" data-page="cart1" data-goodsid="'+item.goodsId+'" data-productid="'+item.productId+'" data-objtype="'+item.objType+'">+</a>\
                          </div>\
                          <p data-role="tips" style="color: red;line-height:30px;">'+tips+'</p>\
                        </td>';
                        var checkedTpl = item.selected ? 'checked="checked"' : '';
                        var objIdentTpl = item.objIdent + '_' + (item.selected ? '1' : '0');
                        checkbox = '<input name="goods" type="checkbox" data-objIdent="'+objIdentTpl+'" value="" '+checkedTpl+'/>';
                    }
                    buyInfoListTpl += '<tr class="cart-product" data-checked=1>\
                                          <td>'+checkbox+'</td>\
                                          <td>\
                                            <div class="p-pic">\
                                              <a href="'+zengpinLink+'" target="_blank"><img src="'+params.image.murl+'" alt="'+params.productName+'"></a>\
                                          </div></td>\
                                          <td class="p-info">\
                                            <div class="p-title"><a target="_blank" href="'+zengpinLink+'">'+params.productName+huangou+zengpin+'</a></div>\
                                            <div class="p-spec fix-empty"></div>\
                                            <div class="p-promotion">\
                                                 <ul>'+liTpl+'</ul>\
                                            </div>\
                                          </td>\
                                          <td class="p-price" data-gwjs="allMoney">¥'+params.price+'</td>'+shuliang+'<td class="p-discount" data-gwjs="saveMoney" data-save="'+item.saveMoney+'">¥'+item.saveMoney+'</td>\
                                          <td class="p-integral" data-gwjs="score" data-score="'+item.score+'">'+item.totalScore+'</td>\
                                          <td class="p-subtotal" data-chae="'+(item.price - item.saveMoney)+'" data-gwjs="real">¥'+item.subtotalPrice+'</td>\
                                          <td class="p-action">'+shoucang+'<i>|</i>\
                                            <a href="javascript:void(0);" class="btn-delete" data-objIdent="'+item.objIdent+'" data-role="settleDel">移除</a>\
                                          </td>\
                                        </tr>';
                })
                $('#product_main_items_list').html(buyInfoListTpl);

                $('[data-role="allMoney"]').html('¥' + res.data.payResultInfo.totalMoney);
                $('[data-role="saveMoney"]').html('¥' + res.data.payResultInfo.savedMoney);
                $('[data-role="totalMoney"]').html('¥' + res.data.payResultInfo.payMoney);
                $('[data-role="fee"]').html('¥' + res.data.payResultInfo.freight);
                $('.subtotal-integral').html(res.data.payResultInfo.giveScore + res.data.payResultInfo.totalNormalScore);
            }

            // 订单优惠
                var orderRuleApplyInfostpl = '';
            if(orderRuleApplyInfos.length) {
                $.each(orderRuleApplyInfos, function(index, item) {
                    if(item.desc!= null) {
                            orderRuleApplyInfostpl += '<li><b>['+item.tag+']</b>'+item.ruleName+'<span style="color:#ef4521;">('+item.desc+')</span></li>';
                    } else {
                        orderRuleApplyInfostpl += '<li><b>['+item.tag+']</b>'+item.ruleName+'</li>';
                    }
                })
                $('[data-role="ddyh"]').html(orderRuleApplyInfostpl);
            } else {

            }
            var tradeUpObjInfostpl = '';
            if(tradeUpObjInfos.length) {
                $.each(tradeUpObjInfos, function(index, item) {
                    if(!item.hasTrade) {
                        tradeUpObjInfostpl += '<li style="position:relative;"><a href="'+item.clickLink+'" target="_blank"><img style="width:748px;cursor:pointer;" src="'+item.adPic+'"/></a><span style="position:absolute;width:96px;height:40px;top:22px;right:26px;cursor:pointer;" data-role="trade" data-ruleid="'+item.ruleId+'" data-objbn="'+item.objBn+'"></span></li>';
                    }
                })
            }
            $('[data-role="ddyh"]').append(tradeUpObjInfostpl);
            if(orderRuleApplyInfos.length <= 0 && tradeUpObjInfos.length <= 0) {
                $('#order_promotion').hide();
            }

            // 多级赠送
            var giveObjInfostpl = '';
            if(giveObjInfos.length) {
                $.each(giveObjInfos, function(index, item) {
                    if(item.showSelect) {
                        giveObjInfostpl += '<div class="djzs-item"><div>'+item.ruleName+'</div>';
                        $.each(item.giveObjInfoList, function(indexDir, itemDir) {
                            if(itemDir.fit) {
                                if(itemDir.selected) {
                                    var inputTpl = '<input type="radio" name="rule'+index+'" data-ruleid="'+item.ruleId+'" data-objtype="'+itemDir.giveObjType+'" data-objid="'+itemDir.giveObjId+'" checked="checked">';
                                } else {
                                    var inputTpl = '<input type="radio" name="rule'+index+'" data-ruleid="'+item.ruleId+'" data-objtype="'+itemDir.giveObjType+'" data-objid="'+itemDir.giveObjId+'">';
                                }
                                giveObjInfostpl += '<div class="djzs-item__inner">\
                                                        <a target="_blank"  href="./info.html?goodsId='+itemDir.goodsId+'&catId='+itemDir.catId+'">\
                                                            <img src="'+itemDir.picUrl+'" alt="'+itemDir.objName+'">\
                                                        </a>\
                                                        <div class="djzs-item__inners">'+inputTpl+'<span   href="javascript:;" title="'+itemDir.objName+'">'+itemDir.objName+'</span>\
                                                        </div>\
                                                    </div>';
                            }
                        })
                        giveObjInfostpl += '</div>';
                    } else {
                        if(index == 0 && giveObjInfos.length == 1) {
                            $('#order_song').hide();
                        }
                    }
                })
                giveObjInfostpl += '<div class="djzs-submit">确定</div>';
                $('[data-role="djzs"]').html(giveObjInfostpl == '<div class="djzs-submit">确定</div>' ? '无' : giveObjInfostpl);
            } else {
                $('#order_song').hide();
            }


            // 以下优惠活动正在进行中
            var orderRuleNotApplyInfosTpl = '';
            if(orderRuleNotApplyInfos.length) {
                $.each(orderRuleNotApplyInfos, function(index, item) {
                    orderRuleNotApplyInfosTpl += '<li><b>['+item.tag+']</b>'+item.ruleName+'</li>';
                })
            } else {
                orderRuleNotApplyInfosTpl += '<li>无</li>'
            }
            $('#contentBox').html(orderRuleNotApplyInfosTpl);
        },
        trandeHandle: function() {
            $(document).on('click', '[data-role="trade"]', function() {
                var $this = $(this);
                var tempLay = iosOverlay({
                    text: '正在处理，请稍等',
                    duration: 10000
                });
                $.ajax({
                    url: wsCommon.host + '/api/cart/cartPayTradeUpUse',
                    dataType: wsCommon.jsonType,
                    data: {
                        ruleId_bn: $this.attr('data-ruleid')+'_'+$this.attr('data-objbn')
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(!res.result) {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                                return;
                            }

                            iosOverlay({
                                text: '换购成功',
                                duration: 1000,
                                onshow: function() {
                                    window.location.reload();
                                }
                            });
                        } else {
                        tempLay.hide()
                          // tempLay.update({
                          //   text: res.reason,
                          //   duration: 1000
                          // })
                            iosOverlay({
                                text: res.reason,
                                duration: 1000
                            });
                        }
                    },
                    error: function(e) {
                    }
                })
            })
        },
        giveHandle: function() {
            $(document).on('click', '.djzs-submit', function() {
                var input = $('.djzs-item').find('input:checked');
                if(input.length == 0) {
                    iosOverlay({
                        text: '请选择多级赠送项目',
                        duration: 1000
                    });
                    return;
                }

                iosOverlay({
                    text: '正在处理，请稍等',
                    duration: 10000
                });
                var giveObjIdentsArr = [];
                $.each(input, function(index, item) {
                    giveObjIdentsArr.push($(item).attr('data-ruleid')+'_'+$(item).attr('data-objtype')+'_'+$(item).attr('data-objid'))
                })

                $.ajax({
                    url: wsCommon.host + '/api/cart/cartPayGive',
                    dataType: wsCommon.jsonType,
                    data: {
                            giveObjIdents: giveObjIdentsArr.join(',')
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(!res.result) {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                                return;
                            }
                            iosOverlay({
                                text: '多级赠送成功',
                                duration: 1000,
                                onshow: function() {
                                    window.location.reload();
                                }
                            });
                        } else {
                            iosOverlay({
                                text: res.reason,
                                duration: 1000
                            });
                        }
                    },
                    error: function(e) {
                    }
                })
            })
        },
        getData: function() {
            $.ajax({
                url: wsCommon.host + '/api/cart/cartPay',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code != 1) return;
                    // if(!res.result) {
                        // wsCommon.setCookie('go_back_link', window.location.href);
                        // window.location.href = './passport-login.html';
                    // }
                    if(res.data == null) {
                        res.data = {};
                        res.data.buyInfoList = [];
                    }
                    var buyInfoList = res.data.buyInfoList ? res.data.buyInfoList : [];
                    var savedMoney = res.data.payResultInfo.savedMoney;
                    // var buyInfoList = [];
                    var orderRuleApplyInfos = res.data.payResultInfo.orderRuleApplyInfos == null ? [] : res.data.payResultInfo.orderRuleApplyInfos;
                    var orderRuleNotApplyInfos = res.data.payResultInfo.orderRuleNotApplyInfos == null ? [] : res.data.payResultInfo.orderRuleNotApplyInfos;

                    var tradeUpObjInfos = res.data.payResultInfo.tradeUpObjInfos == null ? []: res.data.payResultInfo.tradeUpObjInfos;
                    var giveObjInfos = res.data.payResultInfo.giveObjInfos == null ? []: res.data.payResultInfo.giveObjInfos;

                    cart1.renderData(res, buyInfoList, orderRuleApplyInfos, orderRuleNotApplyInfos, tradeUpObjInfos, giveObjInfos, savedMoney);
                },
                error: function() {
                    // console.log('购物车结算页接口返回失败');
                }
            })
        },
        // 删除购物车结算页面的商品(单项)
        delCartSettle: function() {
            var objIdent = null;
            $(document).on('click', '[data-role="dialog-tips-container1"] .action-confirm', function() {
                $.ajax({
                    url: wsCommon.host + '/api/cart/delCart',
                    dataType: wsCommon.jsonType,
                    data: {
                        objIdent: objIdent
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            var obj = {};
                            $.each($('#product_main_items_list').find('input[name=goods]'), function(index, item) {
                                if($(item).prop('checked')) {
                                    var i = $(item).closest('.cart-product').find('.action-quantity-input');
                                    if(i.length && $(item).attr('data-objident') != objIdent) {
                                        obj[$(item).attr('data-objident')] = Number(i.val());
                                    }
                                }
                            })
                            var objStr = JSON.stringify(obj)
                            wsCommon.setCookie('cartIdentInfos', objStr);
                            window.location.reload();
                        }
                    },
                    error: function() {
                        // console.log('购物车删除接口返回失败');
                    }
                })
                $(this).parents('[data-role="dialog-tips-container1"]').hide();
            })
            $(document).on('click', '[data-role="dialog-tips-container1"] .action-cancel', function() {
                $(this).parents('[data-role="dialog-tips-container1"]').hide();
            })

            $(document).on('click', '[data-role="settleDel"]', function() {
                var $this = $(this);
                var $x = $this.offset().left;
    			var $y = $this.offset().top;
                $('[data-role="dialog-tips-container1"]').css({"left":$x-65,"top":$y-90}).show();

                objIdent = $this.attr('data-objident');
            })

        },
        // 删除购物车结算页面的商品(多项)
        delMutiSettle: function() {
            var objidentArr = [];

            $(document).on('click', '[data-role="dialog-tips-container2"] .action-cancel', function() {
                $(this).parents('[data-role="dialog-tips-container2"]').hide();
            })
            $(document).on('click', '[data-role="dialog-tips-container2"] .action-confirm', function() {
                $.ajax({
                    url: wsCommon.host + '/api/cart/delCart',
                    dataType: wsCommon.jsonType,
                    data: {
                        objIdent: objidentArr.join(',')
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            window.location.reload();
                        }
                    },
                    error: function() {
                        // console.log('购物车删除接口返回失败');
                    }
                })
            })
            $(document).on('click', '[data-role="delMuti"]', function() {
                objidentArr = [];
                $.each($('#product_main_items_list input[name="goods"]'), function(index, item) {
                    if($(item).prop('checked')) {
                        objidentArr.push($(item).attr('data-objIdent').substring(0,$(item).attr('data-objIdent').length-2));
                    }
                })

                if(objidentArr.length > 0) {
                    var $this = $(this);
                    var $x = $this.offset().left;
        			var $y = $this.offset().top;
                    $('[data-role="dialog-tips-container2"]').css({"left":$x-65,"top":$y-90}).show();
                } else {
                    iosOverlay({
                        text: '请至少选中一件商品',
                        duration: 1000
                    });
                }
            })
        },
        toggleYouhui: function() {
            //购物车折叠
        	$(".trigger-toggle").each(function(){
        	    $(this).click(function(){
        			if($(this).html()=="-"){
        				$(this).html("+");
        				$(this).parent().siblings().hide();
        			}else{
        				$(this).html("-");
        				$(this).parent().siblings().show();
        			}
        		})
        	})
        },
        toCart2: function() {
            $('.CheckAll').click(function(){
                if($(this).prop('checked')) {
                    $('.cart-product').attr('data-checked', 1);
                } else {
                    $('.cart-product').attr('data-checked', 0);
                }
                $('.CheckAll').attr("checked",this.checked);
               $('input[name="goods"]').attr("checked",this.checked);

               var obj = {};
               $.each($('#product_main_items_list').find('input[name=goods]'), function(indexDir, item) {
                   if(!$(item).is(":hidden")) {
                       if($(item).prop('checked')) {
                           var tempObjient = $(item).attr('data-objident');
                           tempObjient = tempObjient.substring(0, tempObjient.length - 1);
                           $(item).attr('data-objident', tempObjient + '1');
                       } else {
                           var tempObjient = $(item).attr('data-objident');
                           tempObjient = tempObjient.substring(0, tempObjient.length - 1);
                           $(item).attr('data-objident', tempObjient + '0');
                       }

                       var i = $(item).closest('.cart-product').find('.action-quantity-input');
                       if(i.length) {
                           obj[$(item).attr('data-objident')] = Number(i.val());
                       }
                   }
               })
               var objStr = JSON.stringify(obj);
               wsCommon.setCookie('cartIdentInfos', objStr);

               $.ajax({
                   url: wsCommon.host + '/api/cart/cartPay',
                   type: 'post',
                   // dataType: wsCommon.jsonType,
                   data: {
                       cartIdentInfos: JSON.stringify(obj)
                   },
                   success: function(res) {
                       if(res.code == 1) {
                        //    if(!res.result) {
                        //        wsCommon.setCookie('go_back_link', window.location.href);
                        //        window.location.href = './passport-login.html';
                        //        return;
                        //    }

                           $('[data-role="allMoney"]').html('¥' + res.data.payResultInfo.totalMoney);
                           $('[data-role="saveMoney"]').html('¥' + res.data.payResultInfo.savedMoney);
                           $('[data-role="totalMoney"]').html('¥' + res.data.payResultInfo.payMoney);
                           $('[data-role="fee"]').html('¥' + res.data.payResultInfo.freight);
                           $('.subtotal-integral').html(res.data.payResultInfo.giveScore + res.data.payResultInfo.totalNormalScore);

                           if(res.data == null) {
                               res.data = {};
                               res.data.buyInfoList = [];
                           }
                           var buyInfoList = res.data.buyInfoList ? res.data.buyInfoList : [];
                           var savedMoney = res.data.payResultInfo.savedMoney;
                           // var buyInfoList = [];
                           var orderRuleApplyInfos = res.data.payResultInfo.orderRuleApplyInfos == null ? [] : res.data.payResultInfo.orderRuleApplyInfos;
                           var orderRuleNotApplyInfos = res.data.payResultInfo.orderRuleNotApplyInfos == null ? [] : res.data.payResultInfo.orderRuleNotApplyInfos;

                           var tradeUpObjInfos = res.data.payResultInfo.tradeUpObjInfos == null ? []: res.data.payResultInfo.tradeUpObjInfos;
                           var giveObjInfos = res.data.payResultInfo.giveObjInfos == null ? []: res.data.payResultInfo.giveObjInfos;

                           cart1.renderData(res, buyInfoList, orderRuleApplyInfos, orderRuleNotApplyInfos, tradeUpObjInfos, giveObjInfos, savedMoney);

                           // 多级赠送
                           var giveObjInfos = res.data.payResultInfo.giveObjInfos == null ? []: res.data.payResultInfo.giveObjInfos;
                           var giveObjInfostpl = '';
                           if(giveObjInfos.length) {
                               $.each(giveObjInfos, function(index, item) {
                                   if(item.showSelect) {
                                       giveObjInfostpl += '<div class="djzs-item"><div>'+item.ruleName+'</div>';
                                       $.each(item.giveObjInfoList, function(indexDir, itemDir) {
                                           if(itemDir.fit) {
                                               if(itemDir.selected) {
                                                   var inputTpl = '<input type="radio" name="rule'+index+'"         data-ruleid="'+item.ruleId+'" data-objtype="'+itemDir.giveObjType+'" data-objid="'+itemDir.giveObjId+'" checked="checked">';
                                               } else {
                                                   var inputTpl = '<input type="radio" name="rule'+index+'"         data-ruleid="'+item.ruleId+'" data-objtype="'+itemDir.giveObjType+'" data-objid="'+itemDir.giveObjId+'">';
                                               }
                                               giveObjInfostpl += '<div class="djzs-item__inner">\
                                                                       <a target="_blank"  href="./info.html?goodsId='+itemDir.goodsId+'&catId='+itemDir.catId+'">\
                                                                           <img src="'+itemDir.picUrl+'" alt="'+itemDir.objName+'">\
                                                                       </a>\
                                                                       <div class="djzs-item__inners">'+inputTpl+'<span   href="javascript:;" title="'+itemDir.objName+'">'+itemDir.objName+'</span>\
                                                                       </div>\
                                                                   </div>';
                                           }
                                       })
                                       giveObjInfostpl += '</div>';
                                   }
                               })
                               giveObjInfostpl += '<div class="djzs-submit">确定</div>';
                           } else {
                               giveObjInfostpl += '无';
                           }
                           $('[data-role="djzs"]').html(giveObjInfostpl == '<div class="djzs-submit">确定</div>' ? '无' : giveObjInfostpl);


                       } else {
                           iosOverlay({
                               text: res.reason,
                               duration: 1000
                           });
                       }
                   },
                   error: function(e) {
                   }
               })


            });

            $(document).on('click', '#product_main_items_list input[name=goods]', function() {
                var checkedLen = 0;
                var total = $('#product_main_items_list').find('input[name=goods]').length;
                $.each($('#product_main_items_list').find('input[name=goods]'), function(index, item) {
                    if($(item).prop('checked')) {
                        checkedLen++;
                    }
                })
                if(checkedLen < total) {
                    $('.CheckAll').prop('checked', false);
                } else {
                    $('.CheckAll').prop('checked', true);
                }

                var $this = $(this);
                if($this.prop('checked')) {
                    $this.closest('tr').attr('data-checked', 1);
                    var tempObjient = $this.attr('data-objident');
                    tempObjient = tempObjient.substring(0, tempObjient.length - 1);
                    $this.attr('data-objident', tempObjient + '1');
                } else {
                    $this.closest('tr').attr('data-checked', 0);
                    var tempObjient = $this.attr('data-objident');
                    tempObjient = tempObjient.substring(0, tempObjient.length - 1);
                    $this.attr('data-objident', tempObjient + '0');
                }

                var obj = {};
                $.each($('#product_main_items_list').find('input[name=goods]'), function(indexDir, item) {
                    // if($(item).prop('checked')) {
                        var i = $(item).closest('.cart-product').find('.action-quantity-input');
                        if(i.length) {
                            obj[$(item).attr('data-objident')] = Number(i.val());
                        }
                    // }
                })
                var objStr = JSON.stringify(obj);
                wsCommon.setCookie('cartIdentInfos', objStr);

                $.ajax({
                    url: wsCommon.host + '/api/cart/cartPay',
                    // dataType: wsCommon.jsonType,
                    type: 'post',
                    data: {
                        cartIdentInfos: JSON.stringify(obj)
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            // if(!res.result) {
                            //     wsCommon.setCookie('go_back_link', window.location.href);
                            //     window.location.href = './passport-login.html';
                            //     return;
                            // }

                            $('[data-role="allMoney"]').html('¥' + res.data.payResultInfo.totalMoney);
                            $('[data-role="saveMoney"]').html('¥' + res.data.payResultInfo.savedMoney);
                            $('[data-role="totalMoney"]').html('¥' + res.data.payResultInfo.payMoney);
                            $('[data-role="fee"]').html('¥' + res.data.payResultInfo.freight);
                            $('.subtotal-integral').html(res.data.payResultInfo.giveScore + res.data.payResultInfo.totalNormalScore);

                            if(res.data == null) {
                                res.data = {};
                                res.data.buyInfoList = [];
                            }
                            var buyInfoList = res.data.buyInfoList ? res.data.buyInfoList : [];
                            var savedMoney = res.data.payResultInfo.savedMoney;
                            // var buyInfoList = [];
                            var orderRuleApplyInfos = res.data.payResultInfo.orderRuleApplyInfos == null ? [] : res.data.payResultInfo.orderRuleApplyInfos;
                            var orderRuleNotApplyInfos = res.data.payResultInfo.orderRuleNotApplyInfos == null ? [] : res.data.payResultInfo.orderRuleNotApplyInfos;

                            var tradeUpObjInfos = res.data.payResultInfo.tradeUpObjInfos == null ? []: res.data.payResultInfo.tradeUpObjInfos;
                            var giveObjInfos = res.data.payResultInfo.giveObjInfos == null ? []: res.data.payResultInfo.giveObjInfos;

                            cart1.renderData(res, buyInfoList, orderRuleApplyInfos, orderRuleNotApplyInfos, tradeUpObjInfos, giveObjInfos, savedMoney);

                            // 多级赠送
                            var giveObjInfos = res.data.payResultInfo.giveObjInfos == null ? []: res.data.payResultInfo.giveObjInfos;
                            var giveObjInfostpl = '';
                            if(giveObjInfos.length) {
                                $.each(giveObjInfos, function(index, item) {
                                    if(item.showSelect) {
                                        giveObjInfostpl += '<div class="djzs-item"><div>'+item.ruleName+'</div>';
                                        $.each(item.giveObjInfoList, function(indexDir, itemDir) {
                                            if(itemDir.fit) {
                                                if(itemDir.selected) {
                                                    var inputTpl = '<input type="radio" name="rule'+index+'"         data-ruleid="'+item.ruleId+'" data-objtype="'+itemDir.giveObjType+'" data-objid="'+itemDir.giveObjId+'" checked="checked">';
                                                } else {
                                                    var inputTpl = '<input type="radio" name="rule'+index+'"         data-ruleid="'+item.ruleId+'" data-objtype="'+itemDir.giveObjType+'" data-objid="'+itemDir.giveObjId+'">';
                                                }
                                                giveObjInfostpl += '<div class="djzs-item__inner">\
                                                                        <a target="_blank"  href="./info.html?goodsId='+itemDir.goodsId+'&catId='+itemDir.catId+'">\
                                                                            <img src="'+itemDir.picUrl+'" alt="'+itemDir.objName+'">\
                                                                        </a>\
                                                                        <div class="djzs-item__inners">'+inputTpl+'<span  href="javascript:;" title="'+itemDir.objName+'">'+itemDir.objName+'</span>\
                                                                        </div>\
                                                                    </div>';
                                            }
                                        })
                                        giveObjInfostpl += '</div>';
                                    }
                                })
                                giveObjInfostpl += '<div class="djzs-submit">确定</div>';
                            } else {
                                giveObjInfostpl += '无';
                            }
                            $('[data-role="djzs"]').html(giveObjInfostpl == '<div class="djzs-submit">确定</div>' ? '无' : giveObjInfostpl);


                        } else {
                            iosOverlay({
                                text: res.reason,
                                duration: 1000
                            });
                        }
                    },
                    error: function(e) {
                    }
                })

            })

            $(document).on('click', '[data-role="toCart2"]', function() {

                $.ajax({
                    url: wsCommon.host + '/api/member/queryUser',
                    dataType: wsCommon.jsonType,
                    success: function(res) {
                        if(res.code != 1) return;
                        if(!res.result) {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                        } else {
                            var checkedLen = 0;
                            var obj = {};
                            var isEnough = true;
                            var goodsName;

                            $.each($('#product_main_items_list').find('input[name=goods]'), function(indexDir, item) {
                                if(!$(item).is(":hidden")) {
                                    if($(item).prop('checked')) {
                                        var quantity = $(item).closest('tr').find('.p-quantity').find('.action-quantity-input');
                                        if(Number(quantity.val()) > Number(quantity.attr('data-total'))) {
                                            isEnough = false;
                                            goodsName = $(item).closest('tr').find('.p-title a').html();
                                        }
                                        checkedLen++;

                                        var tempObjient = $(item).attr('data-objident');
                                        tempObjient = tempObjient.substring(0, tempObjient.length - 1);
                                        $(item).attr('data-objident', tempObjient + '1');
                                    } else {
                                        var tempObjient = $(item).attr('data-objident');
                                        tempObjient = tempObjient.substring(0, tempObjient.length - 1);
                                        $(item).attr('data-objident', tempObjient + '0');
                                    }

                                    var i = $(item).closest('.cart-product').find('.action-quantity-input');
                                    if(i.length) {
                                        obj[$(item).attr('data-objident')] = Number(i.val());
                                    }
                                }
                            })

                            // $.each($('#product_main_items_list').find('input[name=goods]'), function(index, item) {
                            //     if($(item).prop('checked')) {
                            //         var quantity = $(item).closest('tr').find('.p-quantity').find('.action-quantity-input');
                            //         if(Number(quantity.val()) > Number(quantity.attr('data-total'))) {
                            //             isEnough = false;
                            //             goodsName = $(item).closest('tr').find('.p-title a').html();
                            //         }
                            //         checkedLen++;
                            //         var i = $(item).closest('.cart-product').find('.action-quantity-input');
                            //         if(i.length) {
                            //             obj[$(item).attr('data-objident')] = Number(i.val());
                            //         }
                            //         // else {
                            //         //     obj[$(item).attr('data-objident')] = Number($(item).closest('.cart-product').find('.p-quantity').html());
                            //         // }
                            //
                            //     }
                            // })

                            if(checkedLen == 0) {
                                iosOverlay({
                                    text: "请选择要购买的商品!",
                                    duration: 1500
                                });
                            } else {
                                if(!isEnough) {
                                    iosOverlay({
                                        text: goodsName+"库存不足!",
                                        duration: 1500
                                    });
                                } else {
                                    // todo
                                    var objStr = JSON.stringify(obj)
                                    wsCommon.setCookie('cartIdentInfos', objStr);
                                    window.location.href = './cart2.html';
                                    // console.log(objStr);
                                }

                            }
                        }
                    },
                    error: function() {
                        // console.log('购物车结算页接口返回失败');
                    }
                })
            })
        },
        viewHistory: function() {
            var viewHistory = wsCommon.getCookie('view_history');
            if(viewHistory == null) {
                return;
            }
            $.ajax({
                url: wsCommon.host + '/api/goods/productHistoryList',
                dataType: wsCommon.jsonType,
                data: {
                    productIds: viewHistory
                },
                success: function(res) {
                    if(res.code == 1) {
                        var productsList = res.data.productsList ? res.data.productsList : [];
                        var productsListTpl = '';
                        $.each(productsList, function(index,item) {
                            productsListTpl += '<li class="item">\
                                                    <div class="p-pic">  <a href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" target="_blank" title="'+item.name+'"><img src="'+item.defaultImage.surl+'" alt="'+item.name+'"></a></div>\
                                                    <div class="p-info">\
                                                    	<h3><a href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" target="_blank" title="'+item.name+'">'+item.name+'</a></h3>\
                                                      <p class="p-price">¥'+item.price+'</p>\
                                                      <a href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'" target="_blank" class="btn btn-major"><span><span>立即购买</span></span></a>\
                                                    </div>\
                                                </li>';
                        })
                        $('.view-history').show().find('.history-list').html(productsListTpl);
                    }
                },
                error: function() {
                    // console.log('购物车显示接口返回失败');
                }
            })
        },
        // 收藏
        addFav: function() {
            $(document).on('click', '[data-role="addCartFav"]', function() {
                var $this = $(this);
                $.ajax({
                    url: wsCommon.host + '/api/memberGoods/fav',
                    dataType: wsCommon.jsonType,
                    data: {
                        goodsId: $this.attr('data-goodsid'),
                        productId: $this.attr('data-productid'),
                        goodsName: $this.attr('data-name'),
                        goodsPrice: $this.attr('data-price'),
                        imageDefaultId: $this.attr('data-img')
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                var $x = $this.offset().left;
                    			var $y = $this.offset().top;
                				$("#xtips_txt").html("已成功收藏此商品");
                				$("#xtips_container").css({"opacity":1,"visibility":"visible","left":$x-60,"top":$y-50});
                				$this.replaceWith('<span class="fav-on">已收藏</span>');
                				setTimeout(function () {
                					$("#xtips_container").css({"opacity":0,"visibility":"hidden"});
                				}, 1500);
                            } else {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                            }

                        }
                    },
                    error: function() {
                        // console.log('收藏接口返回失败');
                    }
                })
            })
        },
        init: function() {
            wsCommon.setCookie('isBackCart2', false);
            this.getData();
            this.delCartSettle();
            this.delMutiSettle();
            this.toggleYouhui();
            this.toCart2();
            this.viewHistory();
            this.addFav();
            this.trandeHandle();
            this.giveHandle();
        }
    }

    cart1.init();
})
